package cn.com.java.service.impl;

import cn.com.java.core.HttpRes;
import cn.com.java.core.RedisKey;
import cn.com.java.mapper.SysUserMapper;
import cn.com.java.model.Claims;
import cn.com.java.model.SysUser;
import cn.com.java.service.SysUserService;
import cn.com.java.utils.JWTUtils;
import cn.com.java.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;

    private final RedisUtils redisUtils;


    @Override
    public List<SysUser> getPageAndRole(Page<SysUser> page, QueryWrapper<SysUser> sysRoleQueryWrapper) {
        return sysUserMapper.getPageAndRole(page, sysRoleQueryWrapper);
    }

    @Override
    public HttpRes login(SysUser sysUser) {
        // 认证成功后，返回token
        SysUser byNameUser = getByUserName(sysUser.getUserName());
        if (byNameUser == null) {
            return HttpRes.ERROR("用户不存在", null);
        }
        if (!byNameUser.getPassword().equals(sysUser.getPassword())) {
            return HttpRes.ERROR("用户密码错误", null);
        }
        // jwt实体数据
        Claims claims = new Claims();
        claims.setUserId(String.valueOf(byNameUser.getId()));
        claims.setUsername(byNameUser.getUserName());
        String token = JWTUtils.createToken(claims);
        if(redisUtils.hHasKey(RedisKey.TOKEN_USER, token)){

        } else {
            redisUtils.hset(RedisKey.TOKEN_USER, token, byNameUser, 24 * 60 * 60);
        }
        byNameUser.setToken(token);
        return HttpRes.OK("登录成功", byNameUser);
    }

    @Override
    public SysUser getByUserName(String username) {
        return sysUserMapper.getByUserName(username);
    }
}